package protocol

import (
	"bytes"
	"encoding/binary"
)

const (
	Header    = "headers"
	headerLen = 7
	MLen      = 4
)

func EnPack(message []byte) []byte {
	return append(append([]byte(Header), IntToBytes(len(message))...), message...)
}

// IntToBytes 整形转换成字节
func IntToBytes(n int) []byte {
	x := int32(n)
	bytesBuffer := bytes.NewBuffer([]byte{})
	binary.Write(bytesBuffer, binary.BigEndian, x)
	return bytesBuffer.Bytes()
}
func BytesToInt(b []byte) int {
	bytesBuffer := bytes.NewBuffer(b)
	var x int32
	binary.Read(bytesBuffer, binary.BigEndian, &x)
	return int(x)
}
func DePack(nums []byte, read chan<- []byte) []byte {
	var (
		i int
		l = len(nums)
	)
	for i < l {
		var msgLen int
		if i+headerLen+MLen > l {
			break
		}
		if string(nums[i:i+headerLen]) == Header {
			msgLen = BytesToInt(nums[i+headerLen : i+headerLen+MLen])
			if (msgLen + i + headerLen + MLen) > l {
				break
			}
			read <- nums[i+headerLen+MLen : i+headerLen+MLen+msgLen]
		}
		i += headerLen + MLen + msgLen
	}
	if i == l {
		return nil
	}
	return nums[i:]
}
